package uns.fit.gis.ui;


import java.io.IOException;
import javax.microedition.lcdui.Canvas;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.midlet.MIDlet;

/**
 *
 * @author Nguyen Ngoc Hoan
 */
public class SplashCanvas extends Canvas implements Runnable {

    private Sprite sprite;
    private boolean isLoading;
    private MIDlet midlet;
    private Displayable nextDisplay;

    public void setNextDisplay(Displayable nextDisplay) {
        this.nextDisplay = nextDisplay;
    }

    public SplashCanvas(MIDlet midlet) {
        this.midlet = midlet;
        isLoading = false;
        try {
            Image image = Image.createImage("/splash.png");
            sprite = new Sprite(image, 96, 96);
            sprite.setPosition(this.getWidth() /2 - 48, this.getHeight() / 2 - 48);
            sprite.setFrame(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    protected void paint(Graphics g) {
        sprite.paint(g);
    }

    public void run() {
        while (isLoading) {
            try {
                sprite.setFrame((sprite.getFrame() + 1) % 12);
                repaint();
                Thread.sleep(50);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void start() {
        isLoading = true;
        Display.getDisplay(midlet).setCurrent(this);
        new Thread(this).start();
    }

    public void stop() {
        isLoading = false;
        Display.getDisplay(midlet).setCurrent(nextDisplay);
    }
}
